package com.tanhua.server.serivce;

import com.alibaba.fastjson.JSONArray;
import com.tanhua.domain.db.*;
import com.tanhua.domain.mongo.Conclusion;
import com.tanhua.domain.mongo.Dimension;
import com.tanhua.domain.mongo.SimilarYou;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.api.mongo.ConclusionApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 问卷列表
 */
@Service
public class SoulService {
    @Reference
    private CoverApi coverApi;
    @Reference
    private QuestionsApi questionsApi;
    @Reference
    private OptionsApi optionsApi;
    @Reference
    private ConclusionApi conclusionApi;
    @Reference
    private ReportApi reportApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     *接口名称：测灵魂-问卷列表（学生实战）
     * @return
     */
    public ResponseEntity<Object> questionnaireList() {
        String level = "1";
        if (redisTemplate.hasKey("ANSWER_LEVEL_" + UserHolder.getUserId())){
            level = redisTemplate.opsForValue().get("ANSWER_LEVEL_" + UserHolder.getUserId());
        }
        List<Cover> coverList = coverApi.findCover();
        //生成返回数据
        List<TestSoulVo> testSoulVoList = new ArrayList<>();
        //遍历问卷
        for (Cover cover : coverList) {
            TestSoulVo testSoulVo = new TestSoulVo();
            //调用BeanUtis分装cover到testSoulVo
            BeanUtils.copyProperties(cover, testSoulVo);
            testSoulVo.setReportId(null);
            testSoulVo.setIsLock(1);
             //强转
            if (cover.getId() <= Integer.valueOf(level)) {
                testSoulVo.setIsLock(0);
            }
            //------------------------
            testSoulVo.setStar(cover.getStart());
            testSoulVo.setId(cover.getId().toString());
            //查询questions
            List<Questions> questions = questionsApi.findQuestions(cover.getId());
            //生成list<QuestionsVo>
            List<QuestionsVo> questionsVos = new ArrayList<>();
            //遍历question
            for (Questions question : questions) {

                QuestionsVo questionsVo = new QuestionsVo();
                BeanUtils.copyProperties(question, questionsVo);
                questionsVo.setId(question.getId().toString());

                List<OptionsVo> optionsVos = new ArrayList<>();
                //查出对应的题目
                List<Options> optionsList = optionsApi.findOptions(question.getId());

                //遍历optionList分装到
                for (Options options : optionsList) {

                    OptionsVo optionsVo = new OptionsVo();
                    //查出对应的选项
                    optionsVo.setId(options.getId().toString());
                    //
                    optionsVo.setOption(options.getOption());

                    optionsVos.add(optionsVo);

                }
                questionsVo.setOptions(optionsVos);
                questionsVos.add(questionsVo);
            }
            //查询结果表 初级测试 初级不锁 中高级锁

            //获取当前用户id'
            Long userId = UserHolder.getUserId();
            // Conclusion conclusion = conclusionApi.findConclusionList(userId);
            testSoulVo.setQuestions(questionsVos);

            Conclusion conclusion = conclusionApi.findConclusionList(userId, cover.getLevel());

            if (conclusion == null) {
                testSoulVo.setReportId(null);
            } else {
                testSoulVo.setReportId(conclusion.getId().toHexString());
            }
            testSoulVoList.add(testSoulVo);
        }
        return ResponseEntity.ok(testSoulVoList);
    }

    /**
     * 接口名称：测灵魂-提交问卷（学生实战）
     */
    public ResponseEntity<Object> submitQuestionnaire(String answers) {
        //1.字符串截取 ：“[”..包括两侧括号..“]”
        String[] strings = StringUtils.substringsBetween(answers, "[", "]");
        //2.获取集合对象
        List<Answer> answerList = JSONArray.parseArray(Arrays.toString(strings), Answer.class);

        //求总分
        Integer score = 0;
        for (Answer answer : answerList) {
            score += optionsApi.Count(answer.getOptionId());
        }
        Conclusion conclusion = new Conclusion();
        //拿到等级
        String level = questionsApi.findLevel(answerList.get(0).getQuestionId());

        //封装等级
        conclusion.setLevel(level);
        //封装id
        ObjectId id = ObjectId.get();

        conclusion.setId(id);

        //低于21分 猫头鹰
        if (score < 21) {
            Report report = reportApi.findReport(1);
            BeanUtils.copyProperties(report, conclusion);
            setConclusion(conclusion, score);
            //21分-40分: 白兔
        } else if (score < 40) {
            Report report = reportApi.findReport(2);
            BeanUtils.copyProperties(report, conclusion);
            setConclusion(conclusion, score);
            //  41分-55分: 狐狸
        } else if (score < 55) {
            Report report = reportApi.findReport(3);
            BeanUtils.copyProperties(report, conclusion);
            setConclusion(conclusion, score);
        } else {
            Report report = reportApi.findReport(4);
            BeanUtils.copyProperties(report, conclusion);
            setConclusion(conclusion, score);
        }
        if ("初级".equals(level)) {
            redisTemplate.opsForValue().set("ANSWER_LEVEL_" + UserHolder.getUserId(), "2");
        } else if ("中级".equals(level)) {
            redisTemplate.opsForValue().set("ANSWER_LEVEL_" + UserHolder.getUserId(), "3");
        }
        return ResponseEntity.ok(id.toHexString());
    }
    //  问卷列表，提交问卷方法抽取
    private void setConclusion(Conclusion conclusion, Integer score) {
        Long userId = UserHolder.getUserId();
        //封装用户id
        conclusion.setUserId(userId);
        //封装性别
        UserInfo userInfo = userInfoApi.findById(userId);
        conclusion.setGender(userInfo.getGender());
        //封装总分
        conclusion.setScore(score);
        //维度
        List<String> dimensionStr = Arrays.asList("外向", "判断", "抽象", "理性");
        List<Dimension> dimensions = new ArrayList<>();
        dimensionStr.forEach(s -> {
            Dimension dimension = new Dimension();
            dimension.setKey(s);
            dimension.setValue(RandomUtils.nextInt(75, 95) + "%");
            dimensions.add(dimension);
        });

        conclusion.setDimensions(dimensions);

        //封装与你相似
        List<Long> userIdList = conclusionApi.findSimilarYou(userId, conclusion.getLevel(), score);

        List<SimilarYou> similarYouList = new ArrayList<>();
        for (Long uid : userIdList) {

            UserInfo user = userInfoApi.findById(uid);
            SimilarYou similarYou = new SimilarYou();
            similarYou.setId(user.getId().intValue());
            similarYou.setAvatar(user.getAvatar());
            similarYouList.add(similarYou);
        }
        conclusion.setSimilarYou(similarYouList);
        //保存
        conclusionApi.save(conclusion);
    }

    //查询报告表
    public ResponseEntity<Object> queryReport(String id) {
        ConclusionVo conclusionVo = new ConclusionVo();
        Conclusion conclusion = conclusionApi.queryReport(new ObjectId(id));
        BeanUtils.copyProperties(conclusion, conclusionVo);
        return ResponseEntity.ok(conclusionVo);
    }
}
